package com.gexin.model.system;

import java.util.List;

import com.gexin.common.cache.CacheUtils;
import com.gexin.common.cache.RedisKeyConst;
import com.gexin.common.utils.SQLUtils;
import com.gexin.common.utils.StringUtil;
import com.gexin.model.system.base.BaseAdminDict;
import com.jfinal.plugin.activerecord.Page;

/**
 * 业务名称:  t_admin_dict(数据库字典表) 
 */
@SuppressWarnings("serial")
public class AdminDict extends BaseAdminDict<AdminDict> {
	public static final AdminDict dao = new AdminDict();
	private static final String Cache_Dict_ByKey="cache:dict:byKey:";
	
	/**
	 * 根据  p_key 和  sub_key  获取单个字典的对象
	 * @param p_key  父key
	 * @param s_key  子key
	 * @return  d.busi_name,d.busi_value
	 */
	public  AdminDict  findDictByPKeyAndSKey(String p_key,String s_key){
		String sql = "select d.id,d.busi_name,d.busi_value from t_admin_dict as d where parent_id=(select id from t_admin_dict where parent_id=0 and busi_value=?) where d.busi_value=?  ORDER BY  d.sort_order desc";
		AdminDict   dict =  findFirst(sql,p_key,s_key);
		return  dict;
	}
	
	/**
	 * 获取字典的key  获取下面的值
	 * @param key  key 名称
	 * @return  返回list
	 */
	public  List<AdminDict>   cache_findDictByKey(String key){
		List<AdminDict>    list =  CacheUtils.get(Cache_Dict_ByKey+key);
		if(list!=null  && list.size()>0){
			return  list;
		}
		list  =find("select d.busi_name,d.busi_value from t_admin_dict as d where parent_id=(select id from t_admin_dict where parent_id=0 and busi_value=?) ORDER BY  d.sort_order desc",key);
		if(list.size()>0){
			CacheUtils.set(Cache_Dict_ByKey+key,list,RedisKeyConst.day);//缓存一天
		}
		return  list;
	}
	
	public  void  cache_claer_ByKey(String  key){
		CacheUtils.del(Cache_Dict_ByKey+key);//缓存一天
	}
	
	/**
	 * 查询数据字典所有父类
	 * @return
	 */
	public List<AdminDict> getAllSuperClass() {
		SQLUtils sql =new SQLUtils(" select * from t_admin_dict where parent_id=0 order by sort_order");
		return dao.find(sql.toString());
	}
	
	
	/**
	 * 分页查询数据字典
	 * @param pageNumber
	 * @param pageSize
	 * @param pid
	 * @return
	 */
	public Page<AdminDict> paginateDictByPidDictByPid(int pageNumber, int pageSize,String pid) {
		SQLUtils sql  = new SQLUtils(" from t_admin_dict where 1=1 ");
			if(StringUtil.isEmpty(pid)==false){
				sql.whereEquals("parent_id", pid);
			}
		sql.append(" order by sort_order  desc");

		return paginate(pageNumber, pageSize, " select *  ", sql.toString());
	}
	
	/**
	 * 根据pid 查询
	 * @param pid
	 * @return
	 */
	public List<AdminDict>  getDictByPid(String pid){
		return find(" select * from t_admin_dict where parent_id=? order by sort_order ",pid); 
	}

	/**
	 * 根据字典名称或值查询
	 * @param name
	 * @param value
	 * @return  
	 */
	public List<AdminDict> getByNameOrValue(String sql,String value ,String pid) {
		return find("select * from t_admin_dict WHERE  "+sql+" and parent_id =?",value,pid);
	}
	
}